
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:s_mankey/config/net/api.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/config/router_config.dart';
import 'package:s_mankey/config/storage_manager.dart';
import 'package:s_mankey/generated/I18n.dart';
import 'package:s_mankey/model/search_article_model.dart';
import 'package:s_mankey/model/search_enterprise_model.dart';
import 'package:s_mankey/provider/provider_widget.dart';
import 'package:s_mankey/service/smonkey_repository.dart';
import 'package:s_mankey/ui/widget/error_widget.dart';
import 'package:s_mankey/ui/widget/loading_widget.dart';
import 'package:s_mankey/ui/widget/show_toast.dart';
import 'package:s_mankey/view_model/search_enterprise_vmodel.dart';
import 'package:s_mankey/view_model/search_vm.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class SearchEnterprise extends StatefulWidget {
  @override
  _SearchEnteprise createState() => _SearchEnteprise();
}

class _SearchEnteprise extends State<SearchEnterprise> {
  TextEditingController _controller;
//  SearchEnterpriseVModel model;

  @override
  void initState() {
//    model = SearchEnterpriseVModel();
    _controller = TextEditingController();
    super.initState();
  }
  
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<SearchEnterpriseVModel>(model: SearchEnterpriseVModel(),
    builder: (context, model ,child){
      model.getKeyList();
    return  Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          elevation: 0,
          title: Container(
            height: 44,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30),
                color: AppColor.dividerColor),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: Icon(
                    Icons.search,
                    size: 18,
                  ),
                ),
                Expanded(
                  child: TextField(
                    autofocus: true,
                    controller: _controller,
                    //输入框文字改变时
                    onChanged: (text) {
                      if(text.isEmpty){
                        model.setShowResults(false); //隐藏结果
                      }
                    },
                    //点击软键盘确定时
                    onSubmitted: (text) {
                      print('object#$text');
                      if(text.isEmpty){
                        Toast.toast(context,msg: '请输入搜索内容');
                      }
                      model.setkeyword(text);
                    },
                    decoration: InputDecoration(
//                  contentPadding: EdgeInsets.only(bottom: 9),
                      border: InputBorder.none,
                      hintText: '搜索内容',
                      hintStyle: TextStyle(fontSize: AppFontSize.Size16),
                    ),
                  ),
                ),
              ],
            ),
          ),
          actions: [
        Center(
        child: Padding(
        padding: EdgeInsets.only(right: 10),
      child: GestureDetector(
        onTap: (){
          if(_controller.text.isEmpty){
            Toast.toast(context,msg: '请输入搜索内容');
            return;
          }
          model.setkeyword(_controller.text);
        },
        child: Text(
          '搜索',
          style: TextStyle(fontSize: AppFontSize.Size16, color: Colors.grey),
        ),
      ),
    ),
    ),
          ],
        ),
        body: Container(
          margin: EdgeInsets.fromLTRB(0, 5, 0, 2),
          child: ListView(
            shrinkWrap: true,
            children: <Widget>[

              Padding(
                padding: const EdgeInsets.fromLTRB(10,0,10,0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('历史搜索'),
                    GestureDetector(onTap: (){
                      model.cleanKeyList();
                    }, child: Icon(Icons.delete),),
                  ],
                ),
              ),

              ///搜索历史
              Padding(
                padding: const EdgeInsets.fromLTRB(10,0,10,10),
                child: Offstage(offstage: model.showResults,child: Wrap(children: List.generate(model.keyList?.length?? 0, (index) =>
                GestureDetector(onTap: (){
                  _controller.text = model.keyList[index];
                  model.setkeyword(model.keyList[index]);
                },child: Container(
                    padding: EdgeInsets.fromLTRB(8, 2, 8, 2),
                    margin: EdgeInsets.fromLTRB(0, 5, 10, 5),
                    decoration: BoxDecoration(color: Colors.grey[200],borderRadius: BorderRadius.circular(5)),
                    child: Text(model.keyList[index],style: TextStyle(color: Color(0xff9da0a3),fontSize: AppFontSize.Size14),)),),

                ),),),
              ),

              !model.showResults? Text(''): SearchEnterpriseList(),
            ],
          ),
        ));});
  }
}


///搜索结果
class SearchEnterpriseList extends StatefulWidget {

  @override
  _SearchEnterpriseList createState() => _SearchEnterpriseList();

}

class _SearchEnterpriseList extends State<SearchEnterpriseList>{
  @override
  Widget build(BuildContext context) {

    double imgW =   (AppCustomSize.ScreentWidght- 20);
    double singleImaMaigin = 5.0;
    double singleImgW = (AppCustomSize.ScreentWidght- 20) / 3 - singleImaMaigin ;

    var model = Provider.of<SearchEnterpriseVModel>(context);

    return FutureBuilder(future: SmonkeysRepository.fetchSearchEnterpeise(options: {'company_title': model.keyword}),builder:
        (BuildContext context, AsyncSnapshot snapshot) {

      /// 请求中
      if (snapshot.connectionState != ConnectionState.done) {
        return LoadingWidget();
      }
      /// 请求结束, 错误
      if (snapshot.hasError) {
        // 请求失败，显示错误
        DioError error = snapshot.error;
        return datasErrorWidget(errorTip: error.error.toString());
      }

      List datas = snapshot.data;
      /// 请求成功，显示数据
      return (datas.isEmpty)? datasErrorWidget(errorTip: '没有内容',) :
       ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: datas?.length ?? 0,
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(onTap: (){
//          Navigator.pushNamed(context, RouterName.enterpriseDetail);
            },child: Padding(
              padding: const EdgeInsets.all(10),
              child:

              Column(
                children: [
                  /// 公司名称
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ClipOval(
                        child: Image.network(
                          datas[index]['company_logo'],
                          height: 35,
                          width: 35,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(left: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                datas[index]['company_title'],
                                style: TextStyle(
                                    color: Color(0xff2b2b2b),
                                    fontSize: AppFontSize.Size14),
                              ),
                              Text(
                                datas[index]['area_name'],
                                style: TextStyle(
                                    color: Color(0xff939393),
                                    fontSize: AppFontSize.Size12),
                              ),
                            ],
                          ),
                        ),
                      ),

                      ///TODO： 精选未完成
//                  Offstage(offstage: datas[index]['is_choiceness'] != 0,child: Container(
//                    decoration: BoxDecoration(
//                        gradient: AppColor.gradientColor,
//                        borderRadius: BorderRadius.circular(10)),
//                    child: Container(
//                        margin: EdgeInsets.fromLTRB(8, 4, 8, 4),
//                        child:
//                        Text(
//                          '精选',
//                          style: TextStyle(
//                              fontSize: AppFontSize.Size10,
//                              color: Colors.white),
//                        )),
//                  ),),

                    ],
                  ),
//      中
                  ///内容
                  Container(
                    padding: EdgeInsets.fromLTRB(0,10,0,10),
                    alignment: Alignment(-1, 0),
                    child: Text(
                      datas[index]['company_brief'].trim(),
                      style: TextStyle(

                          fontSize: AppFontSize.Size14, color: Color(0xff71777e)),
                    ),
                  ),

                  ///图片
                  Visibility(visible:  (datas[index]['image'].length != 0),child:  Container(
                    width: imgW ,height: singleImgW,
                    child:
                    Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children:
                        List.generate(datas[index]['image'].take(3).toList().length ,
                              (imgIndex) =>
                              Container(
                                margin: EdgeInsets.fromLTRB((imgIndex == 1)? singleImaMaigin : 0, 0, (imgIndex == 1)? singleImaMaigin : 0, 0),
                                width: singleImgW,height: singleImgW, child: Image.network(datas[index]['image'][imgIndex], fit: BoxFit.cover,),),)
                    ),
                  ),),


                  ///TODO: 这里的圆角还没有实现
                  ///地区
                  Align(alignment: Alignment(-1, 0),child: IntrinsicWidth(child: Container(
                    margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
                    padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(245, 247, 248, 0.7),
                        borderRadius: BorderRadius.circular(3)),
                    child: Row(
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(5, 1.3, 5, 1.3),
                          decoration: BoxDecoration(
//                      color: Color.fromRGBO(145, 247, 248, 0.7),
                          ),
                          child: Text(
                            '•',
                            style: TextStyle(
                                fontSize: AppFontSize.Size14,
                                color: Color(0xff0081ff)),
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
//                      color: Color.fromRGBO(145, 247, 248, 0.7),
                          ),
                          child: Text(
                            '经营范围:',
                            style: TextStyle(
                                fontSize: AppFontSize.Size14,
                                color: Color(0xff0081ff)),
                          ),
                        ),
                        Expanded(child: Container(
                          padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
                          decoration: BoxDecoration(
//                      color: Color.fromRGBO(145, 247, 248, 0.7),
                          ),
                          child: Text(
                            datas[index]['company_business_scope'],
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: AppFontSize.Size14,
                              color: Color(0xffa4afbc),
                            ),
                          ),
                        ),),
                      ],
                    ),
                  ),),),

                  ///TODO: 这里的分割线受父视图限制, 找到超越父视图的方法再回来改
                  Container(height: 1,width:AppCustomSize.ScreentWidght, decoration: BoxDecoration(color: AppColor.dividerColor),child: Text(''), ),
                ],
              ),

            ));
          },
        );});
}}